'''
fuck!
'''
import properties
from selenium import webdriver 
import logging,sys,os,time,datetime,logging  
from selenium.webdriver.support.ui import Select
from selenium.webdriver.remote import webelement

from selenium.common.exceptions import (
        InvalidElementStateException,
        NoSuchAttributeException,
        NoSuchElementException,
        NoSuchFrameException,
        NoSuchWindowException,
        StaleElementReferenceException, 
        WebDriverException,
        UnexpectedTagNameException,
)
 
logger = logging.getLogger("UiTest")  
logger.setLevel(logging.DEBUG)  
# create file handler which logs even debug messages  
fh = logging.FileHandler("log.log")  
fh.setLevel(logging.DEBUG)  
# create console handler with a higher log level  
ch = logging.StreamHandler()  
ch.setLevel(logging.DEBUG)  
# create formatter and add it to the handlers  
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")  
ch.setFormatter(formatter)  
fh.setFormatter(formatter)  
# add the handlers to logger  
logger.addHandler(ch)  
logger.addHandler(fh)   
    
class UiTest:
    
    _all_=['text','password','checkbox','radio','select','textarea']
                    
    def __init__(self,brower=None,browerName=None,profile=None):
        browerName=properties.browerName
        profile=properties.firefoxProfile
        if browerName=='firefox':
            if profile:
                firefoxfile=webdriver.FirefoxProfile(profile_directory=profile)
                firefoxfile.set_preference('webdriver_assume_untrusted_issuer', False)
                firefoxfile.set_preference('capability.policy.default.Window.QueryInterface','allAccess')
                firefoxfile.set_preference('capability.policy.default.Window.frameElement.get','allAccess')
            logger.debug('Starting browser: %s' % browerName)    
            self.brower=webdriver.Firefox()
            #self.brower.execute_script('jQuery.fx.off=true')
            self.brower.set_script_timeout(properties.scripttimeout)
            self.brower.maximize_window();  
            
    #Throw exception
    def throw(self,msg):
        logger.debug(msg)
        self.take_screenshot()
        raise AssertionError(msg)
    
    
    #Open url
    def open(self,url):
        if url is None:
            self.brower.get(properties.url)
            logger.debug('Going to... %s' % properties.url)
        else:
            self.brower.get(url)
            logger.debug('Going to... %s' % url)
        self.wait_page_load()
    
    
    #Wait for element ready
    def wait_element(self,locator,timeout=15):
        start=time.time()
        while time.time()-start<timeout:
            element=self.brower.find_element_by_xpath(locator)
            if element is None:
                time.sleep(1)
            else:
                break
        if element is None:
            msg = ('Element with id: %s does not exist' % locator)
            self.throw(msg)
        else:
            return element
    
    #Verify content in browerSource      
    def contains_content(self,text):
        for element in self.brower.find_elements_by_xpath('//*[text()]'):
            if text in element.text:
                 return True
        return False     
    
    #Wait for content 
    def wait_content(self,text,timeout=15):
        start=time.time()
        flag=False
        while time.time()-start<timeout:
            if  self.contains_content(text):
                flag=True
            time.sleep(1)        
        return flag
     
    #Click element
    def click(self,locator):
        ele=self.wait_element(locator)
        if ele:
            logger.debug('Clicking button %s' % (ele.text!='' and ele.text or ele.get_attribute('value')))
            self.wait_element(locator).click()
             
      
    #Wait page load
    def wait_page_load(self,timeout=properties.pageTimeOut):
        start=time.time()
        while time.time()-start<timeout:
            if self.brower.execute_script('return document.readyState')=='complete':
                return True 
        raise Exception('page load')
    
    #Take a screenshot of the browser window
    def take_screenshot(self,fileName='screenshot.png'):
        logger.debug('capturing screenshot')
        now=datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
        root, extension = os.path.splitext(fileName)
        timeStamp='{0}-{1}{2}'.format(root, now, extension)
        screenshot_file = os.path.join('D:\automation\result', timeStamp)
        self.brower.save_screenshot(screenshot_file)
        
    #Delay to wait something
    def sleep(self,sec):
        logger.debug('Sleeping %s secs'%sec)
        time.sleep(sec)
    
    #SetValue..
    def setValue(self,locator,value):
        ele=self.wait_element(locator)
        try:
            tagName=ele.tag_name.lower()
        except UnexpectedTagNameException:
            msg= 'Element has no tag'
            self.throw(msg)
        try:
            elementType=ele.get_attribute('type')
        except NoSuchAttributeException:
            msg='Element has no type attribute'
            self.throw(msg)
        if tagName=='input':
            if elementType in ('text','password'):
                ele.send_keys(value)
            if elementType in ('radio','checkbox'):
                ele.click() 
        if tagName=='select':
            selectElement=Select(ele)
            selectElement.select_by_visible_text(value)           
        if tagName=='textarea':
            self.brower.execute_script('{0}.innerText={1}',ele,value)
            
                
            
            
        
        
             
ui=UiTest()
ui.open(None)
ui.setValue("//input[@id='kw']",'python')
ui.click("//input[@id='su']")
ui.contains_content('百度百科')

